package seentao.stdev.mobile.log.aop;

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;
import seentao.stdev.mobile.base.vo.BaseVO;
import seentao.stdev.mobile.log.Autitable;
import seentao.stdev.mobile.log.dao.AuditLogDAO;
import seentao.stdev.mobile.log.vo.AuditLogVO;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Component
public aspect AuditLogAspect {

	@Resource
	private AuditLogDAO dao;

	@Resource
	private HttpServletRequest request;

	pointcut writeLog(): execution(public * seentao.stdev.mobile..*DAO.save*(..));
	pointcut writeLog(): execution(public * seentao.stdev.mobile..*DAO.update*(..));
	pointcut writeLog(): execution(public * seentao.stdev.mobile..*DAO.delete*(..));

	before(): writeLog() {
		Object target = thisJoinPoint.getTarget();
		String methodName = thisJoinPoint.getSignature().toShortString();
		Object[] args = thisJoinPoint.getArgs();
		if (args!=null && args.length>0) {
			Object arg = args[0];
			if (arg instanceof BaseVO && (target instanceof Autitable || arg instanceof Autitable)) {
				BaseVO vo = (BaseVO) arg;
				if (methodName.startsWith("save")) {
					if (vo.getId() == null) {
						writeLog(vo, "insert");
					} else {
						writeLog(vo, "update");
					}
				} else if (methodName.startsWith("update")) {
					writeLog(vo, "update");
				} else if (methodName.startsWith("delete")) {
					writeLog(vo, "delete");
				}
			}
		}
	}
	

	private void writeLog(BaseVO vo, String act) {
		AuditLogVO log = new AuditLogVO();
		log.setEntity(getEntity(vo.getClass()));
		log.setRecord(vo.getId());
		log.setOperateAct(act);
		log.setOperateData(getData(vo));
		log.setOperateSubject("~");//TODO 临时
		log.setOperateHost(getHost());
		log.setOperateTimestamp(System.currentTimeMillis());
		dao.save(log);
	}

	private String getEntity(Class<?> entity) {
		return entity.toString();//TODO 临时
	}

	public String getData(BaseVO vo) {
		return JSONObject.toJSONString(vo);
	}

	public String getHost() {
		return request.getRemoteHost();
	}
	

}
